<template>
  <div class="v-slot-editor">
    <div class="left-area">
      <div
        v-for="item in row.values"
        :key="item.id"
        class="_value-column"
        :class="{ '_active-row': selectSlotValueId === item.id }"
        @click="handleSelectClick(item)"
        @contextmenu="propertyModelContextMenu($event, item as any)"
      >
        <component
          :is="propertyManager.getSlotPropertyEditor(row)"
          :instanceId="row.parentId"
          :projectId="projectId"
          :slotData="row"
          :slotValue="item"
          :slotKey="SlotEditKey.SlotValue"
          :row="item"
          :readonly="isModelDisabled"
          :selected="selectSlotValueId === item.id"
        />
      </div>
    </div>
    <div class="right-area">
      <img
        src="statics/icons/app/iconadd.png"
        @click="handleAdd()"
      />
      <img
        src="statics/icons/app/iconreduce.png"
        :class="{ _disabled: !selectSlotValueId }"
        @click="handleDelete()"
      />
      <img
        v-show="row.dataType && row.dataType === PropertyDataType.STRING"
        src="statics/icons/app/iconmodify.svg"
        @click="handleEdit()"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { inject, ref, Ref } from "vue";
import { propertyManager } from "../../PropertyManager";
import { actionManager } from "@/action/ActionManager";
import { CreatePropertyModelTreeSelect } from "@/modules/model/actions/project/CreatePropertyModelTreeSelect";
import { DeleteSlotSpecificationDto, type SlotValue, CreateSpecification } from "../../types";
import { propertyUtil } from "../../PropertyUtil";
import { PropertyKey, PropertyDataType } from "@/constants/Enums";
import TextEditor from "@/modules/model/comps/station/sider/attribute/propertyEditors/modals/TextEditor.vue";
import { BusEvent } from "@/mdesign-lib/mdesign-app.umd.js";
import { propertyModelContextMenu } from "../propertyUtil";
import { ActionKey } from "@/action/ActionKey";
import { SlotEditKey } from "@/constants/constants";

/**
 * 实例表编辑slot 组件
 */
const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

interface SlotData {
  dataType: PropertyDataType;
  hidden: boolean;
  icon: string;
  items: any[];
  moreBtnCondition: string;
  name: string;
  propertyId: string;
  parentId: string;
  projectId: string;
  slotId?: string;
  values: SlotValue[];
  checkMethod?: string;
  valueSpecificationId?: string;
  key: string;
}

const props = defineProps<{
  row: SlotData;
}>();

const selectSlotValueId = ref<string>(props.row.values ? props.row.values[0]?.id : "");
const projectId = app.activeProject!.id;

const handleSelectClick = (slotDataValue: SlotValue) => {
  selectSlotValueId.value = slotDataValue.id;
};

const handleAdd = async () => {
  console.log("handleAdd");
  const data = { ...props.row, key: PropertyKey.Slot_value };
  if (data.dataType == "String") {
    let hasError = false;
    const newText = await TextEditor.popup({
      title: data.name,
      text: ""
    }).catch((err: any) => {
      err && console.error(err);
      hasError = true;
    });
    if (hasError) return;
    const dto: CreateSpecification = {
      projectId: projectId,
      propertyId: data.propertyId,
      slotId: data.slotId,
      parentId: data.parentId,
      value: newText
    };

    await propertyUtil.updatePropertySlotAndFresh(dto);
  }
  if (data.dataType == "Instance") {
    const action = actionManager.getAction(ActionKey.CreatePropertyModelTreeSelect) as CreatePropertyModelTreeSelect;
    data.checkMethod = "checkSlotValueByProperty";
    action.run(data as any, "attrSlots", "插槽");
  }
  if (data.dataType == PropertyDataType.BOOLEAN || data.dataType == "Enum") {
    const dto: CreateSpecification = {
      projectId: data.projectId!,
      propertyId: data.propertyId!,
      slotId: data.slotId,
      parentId: data.parentId!,
      value: "",
      valueSpecificationId: data.valueSpecificationId,
      key: props.row.key
    };
    propertyUtil.updatePropertySlotAndFresh(dto);
  }
};

const handleDelete = async () => {
  if (!selectSlotValueId.value) return;
  const deleteSlot = props.row;
  const dto: DeleteSlotSpecificationDto = {
    projectId: deleteSlot.projectId!,
    specificationId: selectSlotValueId.value,
    slotId: deleteSlot.slotId as string
  };

  await propertyUtil.deleteSpecification(dto);
  selectSlotValueId.value = "";
};

const handleEdit = async () => {
  if (!selectSlotValueId.value) return;
  const row = props.row;
  let hasError = false;
  const newText = await TextEditor.popup({
    title: row.name,
    text: row.values.filter(item => item.id === selectSlotValueId.value)[0]?.value
  }).catch((err: any) => {
    err && console.error(err);
    hasError = true;
  });
  if (hasError) return;
  const dto: CreateSpecification = {
    projectId: projectId,
    propertyId: row.propertyId!,
    slotId: row.slotId,
    parentId: row.parentId,
    value: newText || "",
    valueSpecificationId: selectSlotValueId.value
  };
  const res = await propertyUtil.updatePropertySlotAndFresh(dto);
  // console.log(res, 'processProperty');

  if (res) {
    app.$bus.emit(BusEvent.REFRESH_SLOT, row.parentId);
  }
};
</script>
<style lang="scss">
@import "@/assets/css/theme.scss";
.v-slot-editor {
  display: flex;
  .left-area {
    flex: 1;
    ._value-column {
      line-height: 24px;
      &._active-row {
        background-color: $nth-of-type-bg-color;
      }
    }
  }
  .right-area {
    padding: 4px;
    width: 30px;
    display: flex;
    flex-direction: column;
    border-left: 1px solid #dddddd;
    > img {
      width: 20px;
      height: 14px;
      & + img {
        margin-top: 4px;
      }
    }
    ._disabled {
      cursor: not-allowed;
    }
  }
  .v-slot-input {
    .el-input.is-disabled .el-input__inner {
      cursor: default;
      background-color: unset;
    }
  }
}
</style>
